package common.io.console;

import java.io.*;

/**
 * Created by Gerardo on 2/24/14.
 */
public class StreamDevice implements Terminal {
	private final BufferedReader reader;
	private final PrintWriter writer;

	public StreamDevice(final InputStream in, final PrintStream out) {
		reader = new BufferedReader(new InputStreamReader(in));
		writer = new PrintWriter(out, true);
	}

	@Override
	public Terminal printf(final String fmt, final Object... params) throws TerminalException {
		writer.printf(fmt, params);
		return this;
	}

	@Override
	public String readLine() throws TerminalException {
		try {
			return reader.readLine();
		} catch (IOException e) {
			throw new TerminalException();
		}
	}

	@Override
	public String readLine(final String fmt, final Object... params) throws TerminalException {
		printf(fmt, params);
		return readLine();
	}

	@Override
	public char[] readPassword() throws TerminalException {
		try {
			return reader.readLine().toCharArray();
		} catch (IOException e) {
			throw new TerminalException();
		}
	}

	@Override
	public char[] readPassword(final String fmt, final Object... params) throws TerminalException {
		printf(fmt, params);
		return readPassword();
	}

	@Override
	public Reader reader() throws TerminalException {
		return reader;
	}

	@Override
	public PrintWriter writer() throws TerminalException {
		return writer;
	}
}
